//
//  TJLive_UIButtonExtension.swift
//  KangBoss
//
//  Created by 庞成龙 on 2022/9/25.
//

import Foundation
import UIKit

private var KEY_HIT_TEST_EDGE_INSETS: String = "TJLive_UIButtonHitTestEdgeInsets"

extension UIButton {
    /// 扩展点击区域 举例：  UIEdgeInsetsMake(-50, - 50, -50, - 50)
    public var hitTestEdgeInsets: UIEdgeInsets {
        set {
            var newValueCopy = newValue
            let objCType = NSValue(uiEdgeInsets: .zero).objCType
            let value = NSValue(&newValueCopy, withObjCType: objCType)
            objc_setAssociatedObject(self, &KEY_HIT_TEST_EDGE_INSETS, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            if let value = objc_getAssociatedObject(self, &KEY_HIT_TEST_EDGE_INSETS) as? NSValue {
                var edgeInsets: UIEdgeInsets = .zero
                value.getValue(&edgeInsets)
                return edgeInsets
            } else {
                return .zero
            }
        }
    }

    open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        if (hitTestEdgeInsets == .zero ||
                !self.isEnabled ||
                self.isHidden) {
            return super.point(inside: point, with: event)
        }
        let relativeFrame = bounds
        let hitFrame = relativeFrame.inset(by: hitTestEdgeInsets)
        return hitFrame.contains(point)
    }
}

private var codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
private var isSusspended: Bool = false
private var difference: Int = 0
extension UIButton{
    //倒计时启动
    func countDown(){
        
        if !isSusspended {
            ///监听是否触发home键挂起程序
            NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
            ///监听是否重新进入程序程序.
            NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        }
        
        
        // 倒计时开始,禁止点击事件
        isEnabled = false
        alpha = 0.24
        var remainingCount: Int = getLocalTime() {
            willSet {
//                setAttributedTitle("重新获取(\(newValue)s)".attributed(color: .hex_000000_0_6, font: .regular_14), for: .normal)
                if newValue <= 0 {
//                    setAttributedTitle("重新获取".attributed(color: .hex_000000_0_6, font: .regular_14), for: .normal)
                }
            }
        }
        
        if codeTimer.isCancelled, !isSusspended {
            codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
        }
        
        // 设定这个时间源是每秒循环一次，立即开始
        codeTimer.schedule(deadline: .now(), repeating: .seconds(1))
        // 设定时间源的触发事件
        codeTimer.setEventHandler(handler: {
            // 返回主线程处理一些事件，更新UI等等
            DispatchQueue.main.async { [weak self] in
                // 每秒计时一次
                remainingCount = remainingCount - 1 - difference
                difference = 0
                self?.saveTime(remainingCount)
                // 时间到了取消时间源
                if remainingCount <= 0 {
                    self?.isEnabled = true
                    self?.countDownStop()
                }
            }
        })
        if !isSusspended {
            // 启动时间源
            codeTimer.resume()
            isSusspended = true
        }

    }
    
    //取消倒计时
    func countDownCancel() {
        if !codeTimer.isCancelled {
            codeTimer.cancel()
        }
        isSusspended = false
        NotificationCenter.default.removeObserver(self)
        // 返回主线程
        DispatchQueue.main.async { [weak self] in
            self?.isEnabled = true
            if self?.titleLabel?.text?.count != 0
            {
                self?.setTitle("重新获取", for: .normal)
            }
        }
    }
    
    //停止倒计时
    func countDownStop()  {
        countDownCancel()
        saveTime(0)
    }
    
    /// 是否可发起事件
    func isSendEvent() -> Bool {
        if isSusspended {
            return false
        }
        return true
    }
    
    //获取本地时间戳
    func getLocalTime() -> Int {
        if let time = UserDefaults.standard.string(forKey: "CountDown") {
            return (time == "0" ? 60 : Int(time)) ?? 60
        }
        
        return 60
    }
    
    func saveTime(_ time: Int) {
        
        if time == 0 {
            alpha = 1.0
        }
        
        UserDefaults.standard.setValue(String(time), forKey: "CountDown")
        UserDefaults.standard.synchronize()
    }
    
    //MARK: 监听方法
    @objc func applicationWillResignActive(){
        print("监听是否触发home键挂起程序.")
        UserDefaults.standard.setValue(Date(), forKey: "CountDownDate")
        codeTimer.suspend()
    }
    
    @objc func applicationDidBecomeActive(){
        print("监听是否重新进入程序程序.")
        let oldDate = UserDefaults.standard.value(forKey: "CountDownDate")
        if oldDate != nil {
            let date = oldDate as! Date
            print(date)
            let newDate = Date()
            print(newDate)
            let timeDifference = Int(Date().timeIntervalSince(date))
            if isSusspended {
                difference = timeDifference
            }
            UserDefaults.standard.removeObject(forKey: "CountDownDate")
            UserDefaults.standard.synchronize()
            codeTimer.resume()
        }
    }
}
